import fs from "fs";
import http from "http";
import { promisify } from "util";

export function downloadFileAsync(uri: string, dest: fs.PathLike) {
  return new Promise((resolve, reject) => {
    // 确保dest路径存在
    const file = fs.createWriteStream(dest);

    http.get(uri, (res) => {
      if (res.statusCode !== 200) {
        reject(res.statusCode);
        return;
      }

      // res.on("end", () => {
      //   console.log("download end");
      // });

      // 进度、超时等

      file
        .on("finish", () => {
          file.close();
          resolve(void 0);
        })
        .on("error", (err) => {
          promisify(fs.unlink)(dest);
          reject(err.message);
        });

      res.pipe(file);
    });
  });
}
